package org.telegram.bot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.delay.IDelayEvent;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.telegram.bot.domain.BotChatVerify;
import org.telegram.bot.domain.BotChatVerifyReq;
import org.telegram.bot.domain.BotMessage;
import org.telegram.bot.emums.RedisCacheKeyEnums;
import org.telegram.bot.handle.IBotSendMessage;
import org.telegram.bot.mapper.BotChatVerifyMapper;
import org.telegram.bot.mq.producer.GroupCacheRefreshProducer;
import org.telegram.bot.service.IBotChatVerifyService;
import org.telegram.bot.service.IBotChatWelcomeService;
import org.telegram.telegrambots.meta.api.methods.groupadministration.RestrictChatMember;
import org.telegram.telegrambots.meta.api.methods.updatingmessages.DeleteMessage;
import org.telegram.telegrambots.meta.api.objects.ChatPermissions;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 入群验证Service业务层处理
 *
 * @author wyx
 * @date 2024-11-21
 */
@Slf4j
@Service
public class BotChatVerifyServiceImpl implements IBotChatVerifyService, IBotSendMessage
{
    @Resource
    private BotChatVerifyMapper botChatVerifyMapper;
    
    @Resource
    private IBotChatWelcomeService chatWelcomeService;
    
    @Resource
    private RedisCache redisCache;
    
    @Resource
    private IDelayEvent<BotMessage> botMessageDelayEvent;
    
    @Resource
    private GroupCacheRefreshProducer groupCacheRefreshProducer;
    /**
     * 查询入群验证
     *
     * @param id 入群验证主键
     * @return 入群验证
     */
    @Override
    public BotChatVerify selectBotChatVerifyById(Long id)
    {
        BotChatVerify bean = botChatVerifyMapper.selectById(id);
        if(bean==null){
            bean = botChatVerifyMapper.selectOne(new LambdaUpdateWrapper<BotChatVerify>().eq(BotChatVerify::getChatId,id));
        }
        return bean;
    }

    /**
     * 查询入群验证列表
     *
     * @param botChatVerify 入群验证
     * @return 入群验证
     */
    @Override
    public List<BotChatVerify> selectBotChatVerifyList(BotChatVerify botChatVerify)
    {
        return botChatVerifyMapper.selectBotChatVerifyList(botChatVerify);
    }

    /**
     * 新增入群验证
     *
     * @param botChatVerify 入群验证
     * @return 结果
     */
    @Override
    public int insertBotChatVerify(BotChatVerify botChatVerify)
    {
        botChatVerifyMapper.insert(botChatVerify);
        
        return groupCacheRefreshProducer.sendMessage(botChatVerify.getChatId());
    }

    /**
     * 修改入群验证
     *
     * @param botChatVerify 入群验证
     * @return 结果
     */
    @Override
    public int updateBotChatVerify(BotChatVerify botChatVerify)
    {
        int rows = 0;
        if(botChatVerify.getId()!=null){
            rows = botChatVerifyMapper.updateById(botChatVerify);
        }else{
            if(botChatVerify.getChatId()==null){
                throw new SecurityException("群组信息错误");
            }
            BotChatVerify bean = botChatVerifyMapper.selectOne(new LambdaUpdateWrapper<BotChatVerify>().eq(BotChatVerify::getChatId,botChatVerify.getChatId()));
            if(bean==null){
                rows = insertBotChatVerify(botChatVerify);
            }else{
                botChatVerify.setId(bean.getId());
                rows = botChatVerifyMapper.updateById(botChatVerify);
            }
        }
        return groupCacheRefreshProducer.sendMessage(botChatVerify.getChatId());
    }

    /**
     * 批量删除入群验证
     *
     * @param ids 需要删除的入群验证主键
     * @return 结果
     */
    @Override
    public int deleteBotChatVerifyByIds(Long[] ids)
    {
        List<Long> idsList = Arrays.asList(ids);
        List<BotChatVerify> list = botChatVerifyMapper.selectList(new LambdaQueryWrapper<>(BotChatVerify.class).select(BotChatVerify::getChatId).in(BotChatVerify::getId,idsList));
        botChatVerifyMapper.deleteByIds(idsList);
        
        List<Long> chatIds = list.stream().map(BotChatVerify::getChatId).collect(Collectors.toList());
        groupCacheRefreshProducer.sendMessage(chatIds);
        return ids.length;
    }

    /**
     * 删除入群验证信息
     *
     * @param id 入群验证主键
     * @return 结果
     */
    @Override
    public int deleteBotChatVerifyById(Long id)
    {
        Long chatId = botChatVerifyMapper.selectOne(new LambdaQueryWrapper<>(BotChatVerify.class).select(BotChatVerify::getChatId).eq(BotChatVerify::getId,id)).getChatId();
        botChatVerifyMapper.deleteById(id);
        return groupCacheRefreshProducer.sendMessage(chatId);
    }
    
    /**
     * 初始化群校验
     * @param chatId
     */
    @Override
    public void init(Long chatId) {
        BotChatVerify botChatVerify = botChatVerifyMapper.selectOne(new LambdaUpdateWrapper<BotChatVerify>().eq(BotChatVerify::getChatId, chatId));
        if(botChatVerify==null){
            botChatVerify = new BotChatVerify();
            botChatVerify.setChatId(chatId);
            botChatVerify.setStatus("0");
            botChatVerify.setContent("请在{timeOut}秒内进行验证\n注意：超时将不能发言！");
            botChatVerify.setType("1");
            botChatVerify.setTimeOut(120L);
            botChatVerify.setDelMsgTime(120L);
            botChatVerify.setBanTime(0);
            botChatVerify.setAutoPremium("1");
            insertBotChatVerify(botChatVerify);
        }
    }
    
    @Override
    public boolean newChatMemberVerify(BotChatVerifyReq botChatVerify) {
        //String url = URLUtil.decode(botChatVerify.getInitData());
        BotChatVerifyReq.WebAppInitData data = botChatVerify.getWebAppInitData();
        if(!data.getUser().getId().equals(data.getStart_param().getUserId())){
            throw new ServiceException("无操作权限!", HttpStatus.FORBIDDEN);
        }
        //校验验证码
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + com.ruoyi.common.utils.StringUtils.nvl(botChatVerify.getUuid(), "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!botChatVerify.getCode().equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
        
        BotMessage validate = redisCache.getCacheObject(RedisCacheKeyEnums.BOT_VALIDATE.getKey(data.getStart_param().getBotId().toString(),data.getStart_param().getChatId()+":"+data.getUser().getId()));
        if(validate==null){
            throw new SecurityException("超时验证失败!");
        }
        
        //解除聊天限制
        sendAsync(validate.getBotId(), RestrictChatMember.builder().chatId(validate.getChatId()).userId(botChatVerify.getWebAppInitData().getUser().getId()).permissions(ChatPermissions.builder()
                .canSendMessages(true)
                .canSendOtherMessages(true)
                .canInviteUsers(true)
                .build()).build());
        
        //发送欢迎词
        chatWelcomeService.sendWelcome(validate.getBotId(),validate.getChatId(),validate.getUser());
        
        //删除消息机器人发的验证消息
        sendAsync(validate.getBotId(), DeleteMessage.builder().chatId(validate.getChatId()).messageId(validate.getMessageId()).build());
        
        //删除异步消息任务
        botMessageDelayEvent.removeToDelayQueue(validate);
        
        return true;
    }
}
